<script>
	// require("sdk/libs/strophe");
	let WebIM = (wx.WebIM = require("./utils/WebIM")["default"]);
	let msgStorage = require("./components/chat/msgstorage");
	let msgType = require("./components/chat/msgtype");
	let disp = require("./utils/broadcast");
	let logout = false;
	// let emedia = uni.emedia = require("./emediaSDK/webrtc/src/entry")
	//let emedia = (uni.emedia = require("./emediaSDK/emedia_for_miniProgram"));
	//emedia.config({ useUniappPlugin: true });
	function ack(receiveMsg) {
		// 处理未读消息回执
		var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

		var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
		ackMsg.set({
			id: bodyId,
			to: receiveMsg.from,
		});
		WebIM.conn.send(ackMsg.body);
	}

	function onMessageError(err) {
		if (err.type === "error") {
			uni.showToast({
				title: err.errorText,
			});
			return false;
		}

		return true;
	}

	function getCurrentRoute() {
		let pages = getCurrentPages();
		if (pages.length > 0) {
			let currentPage = pages[pages.length - 1];
			return currentPage.route;
		}
		return "/";
	}



	// 包含陌生人版本
	function calcUnReadSpot(message) {
		let myName = uni.getStorageSync("myUsername");
		uni.getStorageInfo({
			success: function(res) {
				let storageKeys = res.keys;
				let newChatMsgKeys = [];
				let historyChatMsgKeys = [];
				storageKeys.forEach((item) => {
					if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
						newChatMsgKeys.push(item);
					}
				});
				let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
					let chatMsgs;
					chatMsgs = uni.getStorageSync(curMember) || [];
					return result + chatMsgs.length;
				}, 0);

				getApp().globalData.unReadMessageNum = count;
				disp.fire("em.unreadspot", message);
			},
		});
	}

	function saveGroups() {
		var me = this;
		return WebIM.conn.getGroup({
			limit: 50,
			success: function(res) {
				uni.setStorage({
					key: "listGroup",
					data: res.data,
				});
			},
			error: function(err) {
				console.log(err);
			},
		});
	}

	export default {
		globalData: {
			allUsers: {},
			unReadMessageNum: 0,
			userInfo: null,
			saveFriendList: [],
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X
			fromUserName: "",
			fromNickName: "",

			conn: {
				closed: false,
				curOpenOpt: {},

				open(opt) {
					// uni.showLoading({
					//   title: "正在初始化客户端..",
					//   mask: true,
					// });
					this.curOpenOpt = opt;
					WebIM.conn.open(opt);
					this.closed = false;
				},

				reopen() {
					if (this.closed) {
						//this.open(this.curOpenOpt);
						WebIM.conn.open(this.curOpenOpt);
						this.closed = false;
					}
				},
			},
			onLoginSuccess: function(myName) {


				uni.hideLoading();
				uni.redirectTo({
					url: "../chat/chat?myName=" + myName,
				});
			},

			getUserInfo(cb) {
				var me = this;

				if (this.userInfo) {
					typeof cb == "function" && cb(this.userInfo);
				} else {
					// 调用登录接口
					uni.login({
						success() {
							uni.getUserInfo({
								success(res) {
									me.userInfo = res.userInfo;
									typeof cb == "function" && cb(me.userInfo);
								},
							});
						},
					});
				}
			},


			getRoster() {
				let me = this;
				let rosters = {
					success(roster) {

						var users = [];
						var member = [];
						for (let i = 0; i < roster.length; i++) {
							if (roster[i].subscription == "both") {
								users.push(roster[i].name);
							}
						}
						users.push(uni.getStorageSync("myUsername"));
						WebIM.conn.fetchUserInfoById(users, ['nickname', 'avatarurl']).then((res) => {
							console.log(res)
							getApp().globalData.allUsers = res.data;

						})
					},
					error(err) {
						console.log("[main:getRoster]", err);
					},
				};

				WebIM.conn.getRoster(rosters);
			},
			checkIsIPhoneX: function() {
				const me = this;
				uni.getSystemInfo({
					success: function(res) {
						// 根据 model 进行判断
						if (res.model && res.model.search("iPhone X") != -1) {
							me.isIPX = true;
						}
					},
				});
			},
		},
		onLaunch() {
			// 调用 API 从本地缓存中获取数据
			// uni.setInnerAudioOption({
			//   obeyMuteSwitch: false
			// });
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs); //
			
			uni.onTabBarMidButtonTap(()=>{
				alert("dd");
					console.log("点击了")
			        // 这里可以根据 个人需求 做点击处理，
			        // 本人需进行页面跳转。
					// uni.navigateTo({
					// 	url:"../new/new",
					// 	animationType:'slide-in-bottom'
					// })
				});
			
		console.log('App Launch')

			
			
			
			
			
			this.globalData.checkIsIPhoneX();
			// 国际化，设置当前语言
			if (this.vuex_locale) {
				this.$i18n.locale = this.vuex_locale;
				this.$u.api.lang({
					lang: this.vuex_locale
				});
			}
			// 设置底部导航栏角标


			// uni.removeTabBarBadge({
			//   index: 0
			// });


			// this.timer = setInterval(() => {

			// 	if (this.$store.state.isLogin) {
			// 		this.$u.api.getWindCommentsMsgDots({
			// 				userId: this.$store.state.userinfo.id,
			// 			})
			// 			.then(res => {

			// 				if (res.data > 0) {
			// 					console.log("设置" + res.data)
			// 					// uni.setTabBarBadge({
			// 					// 	index: 3,
			// 					// 	text: "" + res.data + ""
			// 					// });
			// 				} else {
			// 					console.log("ddd")
			// 					// uni.removeTabBarBadge({
			// 					// 	index: 3
			// 					// });
			// 				}

			// 			});
			// 	}

			// }, 5000);

		},

		onShow: function() {
			// console.log('App Show')
		},
		onHide: function() {
			// console.log('App Hide')
		}
	}
</script>

<style>
	@import url("/subpackage/static/iconfont/iconfont.css");
</style>
<style lang="scss">
	@import url("/static/css/base.css");
	@import "uview-ui/index.scss";
	@import "pages/common/aidex.scss";
	@import "./app.css";
</style>
